<template>
  <div>
    <label v-if="label">{{ label }}</label>
    <slot></slot>
    <!-- 校验信息显示 -->
    <p v-if="error">{{ error }}</p>
  </div>
</template>

<script>
import Schema from "async-validator"

export default {
  name: "KFormItem",
  props: {
    label: {
      type: String
    },
    prop: {
      type: String
    }
  },

  mounted() {
    //vue3 新变化：没有了$on 解决方案：第三方库mitt使用事务总线
    //                             放到全局注册上 来监听和触发
    this.$mybus.on('validate', () => {
          this.validate()
    })
    this.children.push(this)
  },

  inject: ['form', 'children'],
  data() {
    return {
      error: '' // error为空通过
    }
  },
  methods: {
    validate() {


      const rules = this.form.rules[this.prop]
      const value = this.form.model[this.prop]

      //校验描述对象
      const desc = {[this.prop]: rules}
      //创建Schema实例
      const schema = new Schema(desc)
      return schema.validate({[this.prop]: value}, errors => {
        if(errors) {
          this.error = errors[0].message
        } else {
          this.error = ''
        }
      })
    }
  }
}
</script>

<style scoped>

</style>